#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements reset password request command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import Cookie
import os
import hashlib

import command
import app
import sessions
from db.db_manager import UserDAO, User
from exception import ParameterError

class ResetPassword(command.Command):
    '''
        If user has logged in, updates his password. Otherwise, return error.
    '''
    def is_param_right(self):  
        self.oldPass = self.get_param('oldPass')
        if self.oldPass == None:
            raise ParameterError('error_原密码不能为空')
        
        self.newPass = self.get_param('newPass')
        if self.newPass == None:
            raise ParameterError('error_新密码不能为空')

    def execute(self):
        session = self.get_session()
        user = session.get_attribute('user')
        
        if not user:
            return "error_会话已过期，请重新登录"
        
        session = self.get_session();
        ran = session.get_attribute('random_num')
        password = hashlib.md5("%s%d"%(user.password, ran)).hexdigest()
        
        if user and self.oldPass == password:
            user.password = hashlib.md5(self.newPass).hexdigest()
            UserDAO.persist(user)
            return "success"
        else:
            return "error_原密码不正确"

app.App.start(ResetPassword())
